/* 
登录与注册模块
*/
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api"
import { setToken, getToken, removeToken } from '@/utils/token'
const state = {
  code: '',
  // token: localStorage.getItem('TOKEN'),
  token: getToken(),
  userInfo: ''
}
const actions = {
  /* 获取验证码*/
  async getCode({ commit }, phone) {
    //获取验证码的这个接口把验证码返回，但是正常情况，后台后台把验证码发到用户手机上[省钱]
    let result = await reqGetCode(phone)
    console.log(result);
    if (result.code === 200) {
      console.log('返回的手机验证码:', result.data);
      commit('GETCODE', result.data);
      return 'ok'
    } else {
      return Promise.reject(new Error('验证码获取失败！'))
    }
  },

  /* 用 户注册*/
  async userRegister({ commit }, user) {
    let result = await reqUserRegister(user)
    console.log(result);
    if (result.code === 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('注册失败了！'))
    }
  },

  /* 登录业务【token】 */
  async userLogin({ commit }, data) {
    let result = await reqUserLogin(data)
    console.log('result', result);
    if (result.code == 200) {
      //服务器下发token，用户唯一标识符（uuid）
      //将来经常通过带token找服务器要用户信息进行展示
      console.log('token令牌...', result.data.token);
      //用户应登录成功且获取到token
      commit("USERLOGIN", result.data.token)
      /* 
      持久化存储token
        localStorage.setItem("TOKEN", result.data.token)
      */
      setToken(result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('登录失败！！！'))
    }
  },

  /* 获取用户信息 */
  async getUserInfo({ commit }) {
    let result = await reqUserInfo()
    console.log('获取用户信息', result);
    if (result.code == 200) {
      commit('GETUSERINFO', result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('获取用户信息失败'))
    }
  },

  /* 退出登录 */
  async userLogout({ commit }) {
    //只是向服务器发起一次请求，通知服务器清除token
    let result = await reqLogout()
    if (result.code === 200) {
      commit('CLEAR')
      return 'ok'
    } else {
      return Promise.reject(new Error('退出失败！'))
    }
  }

}
const mutations = {
  GETCODE(state, code) {
    state.code = code;
  },
  USERLOGIN(state, token) {
    state.token = token;
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  //清除本地数据
  CLEAR(state) {
    //吧仓库中相关用户信息清空
    state.token = ''
    state.userInfo = {}
    removeToken() //本地存储数据清空
  }
}
const getters = {}

export default {
  state,
  actions,
  mutations,
  getters
}